/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package IpChat;

/**
 *
 * // as a client, you send out message to destination server IP and port 4000
 * // the following two lines listens to your keyboard input and send keyboard inputs to destination server (servers)
 * // streamOut.writeUTF(console.readLine());
    //        streamOut.flush();
 *
 *
 * @author lubinchen
 */

import java.net.*;
import java.io.*;

public class ChatClient implements Runnable
{  private Socket socket              = null;
   private Thread thread              = null;
   private DataInputStream  console   = null;
   private DataOutputStream streamOut = null;
   private ChatClientThread client    = null;

   // host is requesting to add a new client of serverIp= serverInetAddress
   public ChatClient(InetAddress serverNameInetAddress, int serverPort, String ClientName, callthis call, int index)
   {

      int t=1;

      while(t<=2){

      System.out.println("....You are requesting connection to "+ClientName+". Trial number "+t+". Wait...");

      try
      {  socket = new Socket(serverNameInetAddress, serverPort);
         System.out.println("Congrates! Your request to connecte to " + ClientName+" is accepted.");
         t=100;
         start();
         call.clientconnected.set(index, true);
      }
      catch(UnknownHostException uhe)
      { t++; System.out.println("Host unknown: " + uhe.getMessage()); }
      catch(IOException ioe)

      { t++;System.out.println("Unexpected exception: " + ioe.getMessage()); }
      }
 
    }
   


   // sening keyboard input out
   public void run()
   {  while (thread != null)
      {  try
         {  streamOut.writeUTF(console.readLine());
            streamOut.flush();
         }
         catch(IOException ioe)
         {  System.out.println("Sending error: " + ioe.getMessage());
            stop();
         }
      }
   }


   public void handle(String msg)
   {  if (msg.equals(".quit"))
      {  System.out.println("Leaving here... Press RETURN to exit ...");
         stop();
      }
      else
         System.out.println(msg);
   }


   public void start() throws IOException
   {  console   = new DataInputStream(System.in);
      streamOut = new DataOutputStream(socket.getOutputStream());
      if (thread == null)
      {  client = new ChatClientThread(this, socket);
         thread = new Thread(this);
         thread.start();
      }
   }


   public void stop()
   {  if (thread != null)
      {  thread.stop();
         thread = null;
      }
      try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (socket    != null)  socket.close();
      }
      catch(IOException ioe)
      {  System.out.println("Error closing ..."); }
      client.close();
      client.stop();
   }


   public static void main(String args[])
   {  }


}

